<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha256-CTSx/A06dm1B063156EVh15m6Y67pAjZZaQc89LLSrU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.24/fancybox/fancybox.css" integrity="sha256-vQkngPS8jiHHH0I6ABTZroZk8NPZ7b+MUReOFE9UsXQ=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"rjyblog.gitee.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.18.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":null},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="Java注解原理">
<meta property="og:type" content="article">
<meta property="og:title" content="Java注解原理">
<meta property="og:url" content="https://rjyblog.gitee.io/posts/f45b8d80.html">
<meta property="og:site_name" content="任建勇的博客">
<meta property="og:description" content="Java注解原理">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-09-21T09:46:38.000Z">
<meta property="article:modified_time" content="2023-10-18T08:02:14.470Z">
<meta property="article:author" content="Jason">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://rjyblog.gitee.io/posts/f45b8d80.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://rjyblog.gitee.io/posts/f45b8d80.html","path":"posts/f45b8d80.html","title":"Java注解原理"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Java注解原理 | 任建勇的博客</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">任建勇的博客</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B3%A8%E8%A7%A3%E4%BF%9D%E7%95%99%E7%AD%96%E7%95%A5"><span class="nav-text">注解保留策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B3%A8%E8%A7%A3%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="nav-text">注解的定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B3%A8%E8%A7%A3%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-text">注解的使用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Runtime%E6%97%B6%E6%B3%A8%E8%A7%A3%E7%B1%BB%E7%9C%9F%E8%BA%AB"><span class="nav-text">Runtime时注解类真身</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B3%A8%E8%A7%A3%E7%B1%BB%E5%8F%8D%E5%B0%84%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90"><span class="nav-text">注解类反射源码分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E6%96%87%E7%AB%A0"><span class="nav-text">参考文章</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jason"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">Jason</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">66</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">23</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://rjyblog.gitee.io/posts/f45b8d80.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="Jason">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="任建勇的博客">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Java注解原理 | 任建勇的博客">
      <meta itemprop="description" content="Java注解原理">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java注解原理
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-09-21 17:46:38" itemprop="dateCreated datePublished" datetime="2023-09-21T17:46:38+08:00">2023-09-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-10-18 16:02:14" itemprop="dateModified" datetime="2023-10-18T16:02:14+08:00">2023-10-18</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
    </span>

  
</div>

            <div class="post-description">Java注解原理</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>注解的使用场景可以分为两种：一）编译期间通过注解解析器处理；2）运行期间反射使用；</p>
<h2 id="注解保留策略"><a href="#注解保留策略" class="headerlink" title="注解保留策略"></a>注解保留策略</h2><ul>
<li><code>RetentionPolicy.SOURCE</code> : 编译期可见，但不会写入到.class文件；</li>
<li><code>RetentionPolicy#CLASS</code> : 会写入到.class文件中，但是会被JVM忽略（这是默认策略）；</li>
<li><code>RetentionPolicy#RUNTIME</code> ：注解会被写入到.class文件中，并且JVM运行期间也可见，可以通过反射放射获取到；</li>
</ul>
<h3 id="注解的定义"><a href="#注解的定义" class="headerlink" title="注解的定义"></a>注解的定义</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target(&#123;ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER&#125;)</span></span><br><span class="line"><span class="meta">@Retention(RetentionPolicy.CLASS)</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> MyClass &#123;</span><br><span class="line">    String <span class="title function_">name</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Target(&#123;ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR&#125;)</span></span><br><span class="line"><span class="meta">@Retention(RetentionPolicy.RUNTIME)</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> MyRuntime1 &#123;</span><br><span class="line">    <span class="type">int</span> <span class="title function_">id</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Target(&#123;ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR&#125;)</span></span><br><span class="line"><span class="meta">@Retention(RetentionPolicy.RUNTIME)</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> MyRuntime2 &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Target(&#123;ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR&#125;)</span></span><br><span class="line"><span class="meta">@Retention(RetentionPolicy.SOURCE)</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> MySource &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>编译完成后，每个注解都会生成自己的.class文件，看一下MyClass这个注解的.class文件的内容：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">$ javap -p -v me/demo/MyClass.class</span><br><span class="line">Picked up JAVA_TOOL_OPTIONS: -Duser.language=en -Dfile.encoding=UTF-8</span><br><span class="line">Classfile /F:/demo/JavaDemo/out/production/JavaDemo/me/demo/MyClass.class</span><br><span class="line">  Last modified Sep 21, 2023; size 472 bytes</span><br><span class="line">  MD5 checksum cb49d6b6a5ed7ab9c2b85d731996fb5f</span><br><span class="line">  Compiled from &quot;MyClass.java&quot;</span><br><span class="line">public interface me.demo.MyClass extends java.lang.annotation.Annotation</span><br><span class="line">  minor version: 0</span><br><span class="line">  major version: 61</span><br><span class="line">  flags: (0x2601) ACC_PUBLIC, ACC_INTERFACE, ACC_ABSTRACT, ACC_ANNOTATION</span><br><span class="line">  this_class: #1                          // me/demo/MyClass</span><br><span class="line">  super_class: #3                         // java/lang/Object</span><br><span class="line">  interfaces: 1, fields: 0, methods: 1, attributes: 2</span><br><span class="line">Constant pool:</span><br><span class="line">   #1 = Class              #2             // me/demo/MyClass</span><br><span class="line">   #2 = Utf8               me/demo/MyClass</span><br><span class="line">   #3 = Class              #4             // java/lang/Object</span><br><span class="line">   #4 = Utf8               java/lang/Object</span><br><span class="line">   #5 = Class              #6             // java/lang/annotation/Annotation</span><br><span class="line">   #6 = Utf8               java/lang/annotation/Annotation</span><br><span class="line">   #7 = Utf8               name</span><br><span class="line">   #8 = Utf8               ()Ljava/lang/String;</span><br><span class="line">   #9 = Utf8               SourceFile</span><br><span class="line">  #10 = Utf8               MyClass.java</span><br><span class="line">  #11 = Utf8               RuntimeVisibleAnnotations</span><br><span class="line">  #12 = Utf8               Ljava/lang/annotation/Target;</span><br><span class="line">  #13 = Utf8               value</span><br><span class="line">  #14 = Utf8               Ljava/lang/annotation/ElementType;</span><br><span class="line">  #15 = Utf8               TYPE</span><br><span class="line">  #16 = Utf8               METHOD</span><br><span class="line">  #17 = Utf8               FIELD</span><br><span class="line">  #18 = Utf8               CONSTRUCTOR</span><br><span class="line">  #19 = Utf8               PARAMETER</span><br><span class="line">  #20 = Utf8               Ljava/lang/annotation/Retention;</span><br><span class="line">  #21 = Utf8               Ljava/lang/annotation/RetentionPolicy;</span><br><span class="line">  #22 = Utf8               CLASS</span><br><span class="line">&#123;</span><br><span class="line">  public abstract java.lang.String name();</span><br><span class="line">    descriptor: ()Ljava/lang/String;</span><br><span class="line">    flags: (0x0401) ACC_PUBLIC, ACC_ABSTRACT</span><br><span class="line">&#125;</span><br><span class="line">SourceFile: &quot;MyClass.java&quot;</span><br><span class="line">RuntimeVisibleAnnotations:</span><br><span class="line">  0: #12(#13=[e#14.#15,e#14.#16,e#14.#17,e#14.#18,e#14.#19])</span><br><span class="line">    java.lang.annotation.Target(</span><br><span class="line">      value=[Ljava/lang/annotation/ElementType;.TYPE,Ljava/lang/annotation/ElementType;.METHOD,Ljava/lang/annotation/ElementType;.FIELD,Ljava/lang/annotation/ElementType;.CONSTRUCTOR,Ljava/lang/annotation/ElementType;.PARAMETER]</span><br><span class="line">    )</span><br><span class="line">  1: #20(#13=e#21.#22)</span><br><span class="line">    java.lang.annotation.Retention(</span><br><span class="line">      value=Ljava/lang/annotation/RetentionPolicy;.CLASS</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<p>从MyClass.class文件第7行代码<code>public interface MyClass extends java.lang.annotation.Annotation</code>可以看出来MyClass实际上是继承自Annotation的接口类。这一点从<code>java.lang.Class#getAnnotation</code>这个方法也可以看出来：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//java/lang/Class.java</span></span><br><span class="line">    <span class="keyword">public</span> &lt;A <span class="keyword">extends</span> <span class="title class_">Annotation</span>&gt; A <span class="title function_">getAnnotation</span><span class="params">(Class&lt;A&gt; annotationClass)</span> &#123;</span><br><span class="line">        Objects.requireNonNull(annotationClass);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> (A) annotationData().annotations.get(annotationClass);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="注解的使用"><a href="#注解的使用" class="headerlink" title="注解的使用"></a>注解的使用</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@MySource()</span></span><br><span class="line"><span class="meta">@MyClass(name = &quot;my_class&quot;)</span></span><br><span class="line"><span class="meta">@MyRuntime1(id = 16)</span></span><br><span class="line"><span class="meta">@MyRuntime2</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestAnnotation</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@MyClass(name = &quot;my class constructor&quot;)</span></span><br><span class="line">    <span class="meta">@MyRuntime1(id = 0)</span></span><br><span class="line">    TestAnnotation() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">mDefault</span> <span class="operator">=</span> <span class="string">&quot;Hello&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@MyClass(name = &quot;my class field&quot;)</span></span><br><span class="line">    <span class="meta">@MyRuntime1(id = 1)</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">String</span> <span class="variable">mValue</span> <span class="operator">=</span> mDefault;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@MyClass(name = &quot;my class method&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getValue</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> mValue;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@MyRuntime2</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setValue</span><span class="params">(</span></span><br><span class="line"><span class="params">            <span class="meta">@MyClass(name = &quot;my class param&quot;)</span> String value</span></span><br><span class="line"><span class="params">    )</span> &#123;</span><br><span class="line">        mValue = value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>编译完成后我们使用javap命令看一下TestAnnotation.class的格式：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br></pre></td><td class="code"><pre><span class="line">$ javap -p -v me/demo/TestAnnotation.class</span><br><span class="line">Picked up JAVA_TOOL_OPTIONS: -Duser.language=en -Dfile.encoding=UTF-8</span><br><span class="line">Classfile /F:/demo/JavaDemo/out/production/JavaDemo/me/demo/TestAnnotation.class</span><br><span class="line">  Last modified Sep 21, 2023; size 1062 bytes</span><br><span class="line">  MD5 checksum 8ae94cb155dd4d060085e7c1fef200c5</span><br><span class="line">  Compiled from &quot;TestAnnotation.java&quot;</span><br><span class="line">public class me.demo.TestAnnotation</span><br><span class="line">  minor version: 0</span><br><span class="line">  major version: 61</span><br><span class="line">  flags: (0x0021) ACC_PUBLIC, ACC_SUPER</span><br><span class="line">  this_class: #10                         // me/demo/TestAnnotation</span><br><span class="line">  super_class: #2                         // java/lang/Object</span><br><span class="line">  interfaces: 0, fields: 2, methods: 3, attributes: 3</span><br><span class="line">Constant pool:</span><br><span class="line">   #1 = Methodref          #2.#3          // java/lang/Object.&quot;&lt;init&gt;&quot;:()V</span><br><span class="line">   #2 = Class              #4             // java/lang/Object</span><br><span class="line">   #3 = NameAndType        #5:#6          // &quot;&lt;init&gt;&quot;:()V</span><br><span class="line">   #4 = Utf8               java/lang/Object</span><br><span class="line">   #5 = Utf8               &lt;init&gt;</span><br><span class="line">   #6 = Utf8               ()V</span><br><span class="line">   #7 = String             #8             // Hello</span><br><span class="line">   #8 = Utf8               Hello</span><br><span class="line">   #9 = Fieldref           #10.#11        // me/demo/TestAnnotation.mDefault:Ljava/lang/String;</span><br><span class="line">  #10 = Class              #12            // me/demo/TestAnnotation</span><br><span class="line">  #11 = NameAndType        #13:#14        // mDefault:Ljava/lang/String;</span><br><span class="line">  #12 = Utf8               me/demo/TestAnnotation</span><br><span class="line">  #13 = Utf8               mDefault</span><br><span class="line">  #14 = Utf8               Ljava/lang/String;</span><br><span class="line">  #15 = Fieldref           #10.#16        // me/demo/TestAnnotation.mValue:Ljava/lang/String;</span><br><span class="line">  #16 = NameAndType        #17:#14        // mValue:Ljava/lang/String;</span><br><span class="line">  #17 = Utf8               mValue</span><br><span class="line">  #18 = Utf8               ConstantValue</span><br><span class="line">  #19 = Utf8               RuntimeVisibleAnnotations</span><br><span class="line">  #20 = Utf8               Lme/demo/MyRuntime1;</span><br><span class="line">  #21 = Utf8               id</span><br><span class="line">  #22 = Integer            1</span><br><span class="line">  #23 = Utf8               RuntimeInvisibleAnnotations</span><br><span class="line">  #24 = Utf8               Lme/demo/MyClass;</span><br><span class="line">  #25 = Utf8               name</span><br><span class="line">  #26 = Utf8               my class field</span><br><span class="line">  #27 = Utf8               Code</span><br><span class="line">  #28 = Utf8               LineNumberTable</span><br><span class="line">  #29 = Utf8               LocalVariableTable</span><br><span class="line">  #30 = Utf8               this</span><br><span class="line">  #31 = Utf8               Lme/demo/TestAnnotation;</span><br><span class="line">  #32 = Integer            0</span><br><span class="line">  #33 = Utf8               my class constructor</span><br><span class="line">  #34 = Utf8               getValue</span><br><span class="line">  #35 = Utf8               ()Ljava/lang/String;</span><br><span class="line">  #36 = Utf8               my class method</span><br><span class="line">  #37 = Utf8               setValue</span><br><span class="line">  #38 = Utf8               (Ljava/lang/String;)V</span><br><span class="line">  #39 = Utf8               value</span><br><span class="line">  #40 = Utf8               Lme/demo/MyRuntime2;</span><br><span class="line">  #41 = Utf8               RuntimeInvisibleParameterAnnotations</span><br><span class="line">  #42 = Utf8               my class param</span><br><span class="line">  #43 = Utf8               SourceFile</span><br><span class="line">  #44 = Utf8               TestAnnotation.java</span><br><span class="line">  #45 = Integer            16</span><br><span class="line">  #46 = Utf8               my_class</span><br><span class="line">&#123;</span><br><span class="line">  private final java.lang.String mDefault;</span><br><span class="line">    descriptor: Ljava/lang/String;</span><br><span class="line">    flags: (0x0012) ACC_PRIVATE, ACC_FINAL</span><br><span class="line">    ConstantValue: String Hello</span><br><span class="line"></span><br><span class="line">  private java.lang.String mValue;</span><br><span class="line">    descriptor: Ljava/lang/String;</span><br><span class="line">    flags: (0x0002) ACC_PRIVATE</span><br><span class="line">    RuntimeVisibleAnnotations:</span><br><span class="line">      0: #20(#21=I#22)</span><br><span class="line">        me.demo.MyRuntime1(</span><br><span class="line">          id=1</span><br><span class="line">        )</span><br><span class="line">    RuntimeInvisibleAnnotations:</span><br><span class="line">      0: #24(#25=s#26)</span><br><span class="line">        me.demo.MyClass(</span><br><span class="line">          name=&quot;my class field&quot;</span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">  me.demo.TestAnnotation();</span><br><span class="line">    descriptor: ()V</span><br><span class="line">    flags: (0x0000)</span><br><span class="line">    Code:</span><br><span class="line">      stack=2, locals=1, args_size=1</span><br><span class="line">         0: aload_0</span><br><span class="line">         1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V</span><br><span class="line">         4: aload_0</span><br><span class="line">         5: ldc           #7                  // String Hello</span><br><span class="line">         7: putfield      #9                  // Field mDefault:Ljava/lang/String;</span><br><span class="line">        10: aload_0</span><br><span class="line">        11: ldc           #7                  // String Hello</span><br><span class="line">        13: putfield      #15                 // Field mValue:Ljava/lang/String;</span><br><span class="line">        16: return</span><br><span class="line">      LineNumberTable:</span><br><span class="line">        line 11: 0</span><br><span class="line">        line 14: 4</span><br><span class="line">        line 16: 10</span><br><span class="line">        line 12: 16</span><br><span class="line">      LocalVariableTable:</span><br><span class="line">        Start  Length  Slot  Name   Signature</span><br><span class="line">            0      17     0  this   Lme/demo/TestAnnotation;</span><br><span class="line">    RuntimeVisibleAnnotations:</span><br><span class="line">      0: #20(#21=I#32)</span><br><span class="line">        me.demo.MyRuntime1(</span><br><span class="line">          id=0</span><br><span class="line">        )</span><br><span class="line">    RuntimeInvisibleAnnotations:</span><br><span class="line">      0: #24(#25=s#33)</span><br><span class="line">        me.demo.MyClass(</span><br><span class="line">          name=&quot;my class constructor&quot;</span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">  public java.lang.String getValue();</span><br><span class="line">    descriptor: ()Ljava/lang/String;</span><br><span class="line">    flags: (0x0001) ACC_PUBLIC</span><br><span class="line">    Code:</span><br><span class="line">      stack=1, locals=1, args_size=1</span><br><span class="line">         0: aload_0</span><br><span class="line">         1: getfield      #15                 // Field mValue:Ljava/lang/String;</span><br><span class="line">         4: areturn</span><br><span class="line">      LineNumberTable:</span><br><span class="line">        line 22: 0</span><br><span class="line">      LocalVariableTable:</span><br><span class="line">        Start  Length  Slot  Name   Signature</span><br><span class="line">            0       5     0  this   Lme/demo/TestAnnotation;</span><br><span class="line">    RuntimeInvisibleAnnotations:</span><br><span class="line">      0: #24(#25=s#36)</span><br><span class="line">        me.demo.MyClass(</span><br><span class="line">          name=&quot;my class method&quot;</span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">  public void setValue(java.lang.String);</span><br><span class="line">    descriptor: (Ljava/lang/String;)V</span><br><span class="line">    flags: (0x0001) ACC_PUBLIC</span><br><span class="line">    Code:</span><br><span class="line">      stack=2, locals=2, args_size=2</span><br><span class="line">         0: aload_0</span><br><span class="line">         1: aload_1</span><br><span class="line">         2: putfield      #15                 // Field mValue:Ljava/lang/String;</span><br><span class="line">         5: return</span><br><span class="line">      LineNumberTable:</span><br><span class="line">        line 29: 0</span><br><span class="line">        line 30: 5</span><br><span class="line">      LocalVariableTable:</span><br><span class="line">        Start  Length  Slot  Name   Signature</span><br><span class="line">            0       6     0  this   Lme/demo/TestAnnotation;</span><br><span class="line">            0       6     1 value   Ljava/lang/String;</span><br><span class="line">    RuntimeVisibleAnnotations:</span><br><span class="line">      0: #40()</span><br><span class="line">        me.demo.MyRuntime2</span><br><span class="line">    RuntimeInvisibleParameterAnnotations:</span><br><span class="line">      parameter 0:</span><br><span class="line">        0: #24(#25=s#42)</span><br><span class="line">          me.demo.MyClass(</span><br><span class="line">            name=&quot;my class param&quot;</span><br><span class="line">          )</span><br><span class="line">&#125;</span><br><span class="line">SourceFile: &quot;TestAnnotation.java&quot;</span><br><span class="line">RuntimeVisibleAnnotations:</span><br><span class="line">  0: #20(#21=I#45)</span><br><span class="line">    me.demo.MyRuntime1(</span><br><span class="line">      id=16</span><br><span class="line">    )</span><br><span class="line">  1: #40()</span><br><span class="line">    me.demo.MyRuntime2</span><br><span class="line">RuntimeInvisibleAnnotations:</span><br><span class="line">  0: #24(#25=s#46)</span><br><span class="line">    me.demo.MyClass(</span><br><span class="line">      name=&quot;my_class&quot;</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<ul>
<li>保留策略是<code>RetentionPolicy.CLASS</code>的注解会保存在<code>RuntimeInvisibleAnnotations</code>列表中；</li>
<li>保留策略是<code>RetentionPolicy.RUNTIME</code>的注解类会被放在<code>RuntimeVisibleAnnotations</code>列表中；</li>
<li>保留策略是<code>RetentionPolicy.SOURCE</code>的注解不在TestAnnotation.class中；</li>
<li>方法参数的注解则保存在<code>RuntimeInvisibleParameterAnnotations</code>列表中；</li>
</ul>
<h2 id="Runtime时注解类真身"><a href="#Runtime时注解类真身" class="headerlink" title="Runtime时注解类真身"></a>Runtime时注解类真身</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Main</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        Class&lt;TestAnnotation&gt; testCls = TestAnnotation.class;</span><br><span class="line">        System.out.println(testCls.getAnnotation(MyRuntime1.class).getClass());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>日志输出结果是：<code>class jdk.proxy2.$Proxy1</code>，而不是MyRuntime1。这是为什么呢？实际上，当我们反射获取注解时，虚拟机会通过动态代理的方式生成了一个代理类返回。通过设置虚拟机参数<code>-Djdk.proxy.ProxyGenerator.saveGeneratedFiles=true</code>，虚拟机会把生成的代理类保存为文件。</p>
<p>进入.class文件的生成目录，使用如下命令运行main函数：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">java -Djdk.proxy.ProxyGenerator.saveGeneratedFiles=true -Dfile.encoding=UTF-8 -classpath ./ Main</span><br></pre></td></tr></table></figure>

<p>执行完上述命令后，在当前目录的<code>./jdk/proxy2/</code>目录下就可以找到<code>$Proxy1.class</code>文件。</p>
<p>另外一种简单的方式就是在java main函数最前面（只要在执行反射获取注解之前就行）添加如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">System.setProperty(<span class="string">&quot;jdk.proxy.ProxyGenerator.saveGeneratedFiles&quot;</span>, <span class="string">&quot;true&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>IDEA运行后会在工程主目录下的<code>jdk/proxy2/</code>文件夹中保存动态代理类。通过IDEA打开文件后可以看到如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">$Proxy1</span> <span class="keyword">extends</span> <span class="title class_">Proxy</span> <span class="keyword">implements</span> <span class="title class_">MyRuntime1</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Method m0;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Method m1;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Method m2;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Method m3;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Method m4;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> $Proxy1(InvocationHandler var1) &#123;</span><br><span class="line">        <span class="built_in">super</span>(var1);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="type">int</span> <span class="title function_">hashCode</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (Integer)<span class="built_in">super</span>.h.invoke(<span class="built_in">this</span>, m0, (Object[])<span class="literal">null</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="type">boolean</span> <span class="title function_">equals</span><span class="params">(Object var1)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (Boolean)<span class="built_in">super</span>.h.invoke(<span class="built_in">this</span>, m1, <span class="keyword">new</span> <span class="title class_">Object</span>[]&#123;var1&#125;);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (String)<span class="built_in">super</span>.h.invoke(<span class="built_in">this</span>, m2, (Object[])<span class="literal">null</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="type">int</span> <span class="title function_">id</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (Integer)<span class="built_in">super</span>.h.invoke(<span class="built_in">this</span>, m3, (Object[])<span class="literal">null</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Class <span class="title function_">annotationType</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> (Class)<span class="built_in">super</span>.h.invoke(<span class="built_in">this</span>, m4, (Object[])<span class="literal">null</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (RuntimeException | Error var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> var2;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UndeclaredThrowableException</span>(var3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            m0 = Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>).getMethod(<span class="string">&quot;hashCode&quot;</span>);</span><br><span class="line">            m1 = Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>).getMethod(<span class="string">&quot;equals&quot;</span>, Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>));</span><br><span class="line">            m2 = Class.forName(<span class="string">&quot;java.lang.Object&quot;</span>).getMethod(<span class="string">&quot;toString&quot;</span>);</span><br><span class="line">            m3 = Class.forName(<span class="string">&quot;me.demo.MyRuntime1&quot;</span>).getMethod(<span class="string">&quot;id&quot;</span>);</span><br><span class="line">            m4 = Class.forName(<span class="string">&quot;me.demo.MyRuntime1&quot;</span>).getMethod(<span class="string">&quot;annotationType&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchMethodException var2) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NoSuchMethodError</span>(var2.getMessage());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ClassNotFoundException var3) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">NoClassDefFoundError</span>(var3.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> MethodHandles.Lookup <span class="title function_">proxyClassLookup</span><span class="params">(MethodHandles.Lookup var0)</span> <span class="keyword">throws</span> IllegalAccessException &#123;</span><br><span class="line">        <span class="keyword">if</span> (var0.lookupClass() == Proxy.class &amp;&amp; var0.hasFullPrivilegeAccess()) &#123;</span><br><span class="line">            <span class="keyword">return</span> MethodHandles.lookup();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalAccessException</span>(var0.toString());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="注解类反射源码分析"><a href="#注解类反射源码分析" class="headerlink" title="注解类反射源码分析"></a>注解类反射源码分析</h2><p>Class/Method/Field都有自己的反射获取注解的接口，如下：<code>java.lang.Class#getAnnotation</code> <code>java.lang.reflect.Method#getAnnotation</code> <code>java.lang.reflect.Field#getAnnotation</code>。注意：当通过<code>java.lang.Class#getAnnotation</code>来获取Class的注解时，只能获取Class本身的注解，而不能获取到Class中方法和成员变量的注解。反射获取注解实例代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">testCls.getAnnotation(MyRuntime1.class);</span><br><span class="line">testCls.getMethod(<span class="string">&quot;setValue&quot;</span>, String.class).getAnnotation(MyRuntime1.class);</span><br><span class="line">testCls.getField(<span class="string">&quot;mValue&quot;</span>).getAnnotation(MyRuntime1.class);</span><br></pre></td></tr></table></figure>

<p>当调用<code>java.lang.Class#getAnnotation(Class&lt;A&gt; annotationClass)</code>方法反射获取注解类时，会把这个类本身的注解全部进行解析，然后生成对应的动态代理类，注册到map列表中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//java/lang/Class.java</span></span><br><span class="line">    <span class="keyword">public</span> &lt;A <span class="keyword">extends</span> <span class="title class_">Annotation</span>&gt; A <span class="title function_">getAnnotation</span><span class="params">(Class&lt;A&gt; annotationClass)</span> &#123;</span><br><span class="line">        Objects.requireNonNull(annotationClass);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> (A) annotationData().annotations.get(annotationClass);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> AnnotationData <span class="title function_">annotationData</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="literal">true</span>) &#123; <span class="comment">// retry loop</span></span><br><span class="line">            <span class="type">AnnotationData</span> <span class="variable">annotationData</span> <span class="operator">=</span> <span class="built_in">this</span>.annotationData;</span><br><span class="line">            <span class="type">int</span> <span class="variable">classRedefinedCount</span> <span class="operator">=</span> <span class="built_in">this</span>.classRedefinedCount;</span><br><span class="line">            <span class="keyword">if</span> (annotationData != <span class="literal">null</span> &amp;&amp;</span><br><span class="line">                annotationData.redefinedCount == classRedefinedCount) &#123;</span><br><span class="line">                <span class="keyword">return</span> annotationData;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// null or stale annotationData -&gt; optimistically create new instance</span></span><br><span class="line">            <span class="type">AnnotationData</span> <span class="variable">newAnnotationData</span> <span class="operator">=</span> createAnnotationData(classRedefinedCount);</span><br><span class="line">            <span class="comment">// try to install it</span></span><br><span class="line">            <span class="keyword">if</span> (Atomic.casAnnotationData(<span class="built_in">this</span>, annotationData, newAnnotationData)) &#123;</span><br><span class="line">                <span class="comment">// successfully installed new AnnotationData</span></span><br><span class="line">                <span class="keyword">return</span> newAnnotationData;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="参考文章"><a href="#参考文章" class="headerlink" title="参考文章"></a>参考文章</h2><p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.cnblogs.com/yangming1996/p/9295168.html">JAVA 注解的基本原理</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java/" rel="tag"># Java</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/posts/d01e7370.html" rel="prev" title="Android View Measure源码分析">
                  <i class="fa fa-angle-left"></i> Android View Measure源码分析
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/posts/68833f9e.html" rel="next" title="Bitmap内存分配以及回收">
                  Bitmap内存分配以及回收 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Jason</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener external nofollow noreferrer" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener external nofollow noreferrer" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.24/fancybox/fancybox.umd.js" integrity="sha256-oyhjPiYRWGXaAt+ny/mTMWOnN1GBoZDUQnzzgC7FRI4=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>


  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":{"light":"default","dark":"dark"},"js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.5.0/mermaid.min.js","integrity":"sha256-K7oJiQlDulzl24ZUFOywuYme1JqBBvQzK6m8qHjt9Gk="}}</script>
  <script type="module" src="/js/zenuml-definition-074a43fa.js"></script>
  <script type="module" src="/js/mermaid-zenuml.esm.min.mjs"></script>
  <script src="/js/third-party/tags/mermaid.js"></script>


  <script src="/js/third-party/fancybox.js"></script>



  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>



</body>
</html>
